//生成token
const jwt = require("jsonwebtoken");
const config = require("../config.js");
//导入数据库模块
const db = require("../db/index");
const handleSql = require("../utils/handleSql");
//登录的路由函数
exports.login = async (req, res) => {
  console.log(req.body);
  //判断账号是否存在
  const sql1 = "select * from vue_users where username=?";
  const result = await handleSql(sql1, req.body.username);
  //判断密码是否正确
  if (!result[0]) return res.error("用户不存在", 401);
  if (result[0].password !== req.body.password)
    return res.error("密码错误", 404);
  if (result[0].type !== req.body.type) return res.error("权限错误", 404);
  //生成token
  const user = { ...result[0], token: "", password: "", user_pic: "" };
  const token = jwt.sign(user, config.jwtSerectKey, {
    expiresIn: config.expireIn,
  });
  //存储token
  const sql2 = "update vue_users set token=? where username=?";
  const result2 = await handleSql(sql2, token, req.body.username);
  if (result2.affectedRows !== 1) {
    console.log("存储token出错");
  }
  //将token传给前端
  res.json({
    status: 200,
    message: "登录成功",
    token: "Bearer " + token,
  });
};
//获取个人信息
exports.getUserDataByToken = async (req, res) => {
  const sql =
    "select id,username,user_pic,class,sex,address,createTime,modifytime,type from vue_users where id=?";
  const result = await handleSql(sql, req.user.id);
  if (result.length !== 1) return res.error("获取用户个人信息失败", 500);
  console.log(result);
  res.json({
    status: 200,
    message: "获取个人信息成功",
    data: result[0],
  });
};
